package controllers

import (
	"encoding/json"
	"io/ioutil"
	"mypassword/models"
	"mypassword/services"
	"strconv"
	"time"
)

type AccountController struct {
	BaseController
	accountService *services.AccountService
}

func (c *AccountController) Prepare() {
	c.BaseController.Prepare()
	c.accountService = services.NewAccountService()
}

func (c *AccountController) List() {
	accounts, err := c.accountService.GetAll()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": err.Error(),
		}
	} else {
		c.Data["json"] = map[string]interface{}{
			"success": true,
			"data":    accounts,
		}
	}
	c.ServeJSON()
}

func (c *AccountController) Create() {
	// 读取请求体
	body, err := ioutil.ReadAll(c.Ctx.Request.Body)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "读取请求数据失败",
		}
		c.ServeJSON()
		return
	}

	// 打印原始请求数据（调试用）
	println("Raw request body:", string(body))

	var account models.Account
	if err := json.Unmarshal(body, &account); err != nil {
		println("JSON unmarshal error:", err.Error()) // 调试用
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 打印解析后的数据（调试用）
	println("Parsed account:", account.SystemName, account.Username, account.Password)

	// 验证必填字段
	if account.SystemName == "" || account.Username == "" || account.Password == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统名称、账户名称和密码不能为空",
		}
		c.ServeJSON()
		return
	}

	account.CreatedTime = time.Now()
	account.UpdatedTime = time.Now()

	if err := c.accountService.Create(&account); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建失败: " + err.Error(),
		}
	} else {
		c.Data["json"] = map[string]interface{}{
			"success": true,
			"data":    account,
		}
	}
	c.ServeJSON()
}

func (c *AccountController) Update() {
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)

	// 读取请求体
	body, err := ioutil.ReadAll(c.Ctx.Request.Body)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "读取请求数据失败",
		}
		c.ServeJSON()
		return
	}

	// 打印原始请求数据（调试用）
	println("Raw request body:", string(body))

	var account models.Account
	if err := json.Unmarshal(body, &account); err != nil {
		println("JSON unmarshal error:", err.Error()) // 调试用
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 打印解析后的数据（调试用）
	println("Parsed account:", account.SystemName, account.Username, account.Password)

	// 验证必填字段
	if account.SystemName == "" || account.Username == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "系统名称和账户名称不能为空",
		}
		c.ServeJSON()
		return
	}

	account.Id = id
	account.UpdatedTime = time.Now()

	if err := c.accountService.Update(&account); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新失败: " + err.Error(),
		}
	} else {
		c.Data["json"] = map[string]interface{}{
			"success": true,
			"data":    account,
		}
	}
	c.ServeJSON()
}

func (c *AccountController) DecryptPassword() {
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)

	// 从上下文中获取 isSecondPassword，而不是从 session
	isSecondPassword := c.Ctx.Input.GetData("isSecondPassword").(bool)

	password, err := c.accountService.DecryptPassword(id, isSecondPassword)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": err.Error(),
		}
	} else {
		c.Data["json"] = map[string]interface{}{
			"success": true,
			"data":    password,
		}
	}
	c.ServeJSON()
}

func (c *AccountController) Delete() {
	id, err := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的ID",
		}
		c.ServeJSON()
		return
	}

	if err := c.accountService.Delete(id); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除失败: " + err.Error(),
		}
	} else {
		c.Data["json"] = map[string]interface{}{
			"success": true,
			"message": "删除成功",
		}
	}
	c.ServeJSON()
}
